<template>
  <van-popup
    :show="visible"
    :close-on-click-overlay="false"
    round
    safe-area-inset-bottom
    safe-area-inset-top
    position="bottom"
    class="m-picker"
  >
    <van-picker
      :show-toolbar="showToolbar"
      :title="title"
      :columns="data"
      :default-index="current"
      :columns-field-names="customFieldName"
      :option-height="itemHeight"
      @cancel="cancel"
      @confirm="confirm"
    >
      <slot name="toolbar"></slot>
    </van-picker>
  </van-popup>
</template>
<script>
import { computed, toRefs } from 'vue'
export default {
  name: 'MPicker',
  emits: ['update:show', 'update:modelValue'],
  props: {
    modelValue: {
      type: [String, Number],
    },
    visible: {
      type: Boolean,
    },
    title: {
      type: String,
    },
    customFieldName: {
      type: Object,
    },
    height: {
      type: Number,
      default: 280,
    },
    data: {
      type: Array,
      default: () => [],
    },
    itemHeight: {
      type: [String, Number],
    },
    readonly: {
      type: Boolean,
    },
    showToolbar: {
      type: Boolean,
      default: true,
    },
  },
  setup (props, { emit }) {
    const { visible, modelValue, title, height, data, readonly, itemHeight, customFieldName } = toRefs(props)

    const current = computed(() => {
      return modelValue.value
        ? data.value.findIndex((ret) => ret.value === modelValue.value)
        : 0
    })
    const keys = computed(() => data.value.map((ret) => ret.label))

    const confirm = () => {
      emit('update:modelValue', modelValue.value)
      cancel()
    }
    const cancel = () => {
      emit('update:show', false)
    }
    return {
      visible,
      current,
      title,
      height,
      data,
      itemHeight,
      customFieldName,
      keys,
      readonly,
      cancel,
      confirm,
    }
  }
}
</script>
